<template>
  <div class="body1">
    <div class="no-print el-button-print">
      <el-button @click="exportPDF">导出为pdf</el-button>
    </div>
    <div class="body2" id="pdfDom" :class="{ 'pdf-export': isPdfExport }">
      <div class="title">
        <div class="biaotididian">{{ agencyName }}</div>
        <div class="biaoti">送达地址确认书</div>
      </div>
      <table class="tableStyle">
        <colgroup>
          <col width="16%">
          <col width="16%">
          <col width="25%">
          <col width="13%">
          <col width="30%">
        </colgroup>
        <tbody>
          <tr>
            <td style="text-align: center;">立案编号</td>
            <td colspan="4">
              <el-input v-model="form.a1" :resize="'none'" autosize class="areaInputStyle" type="textarea"
                maxlength="27" />
            </td>
          </tr>
          <tr>
            <td style="text-align: center;">案&nbsp;&nbsp;&nbsp;&nbsp;由</td>
            <td colspan="4">
              <el-input v-model="form.a2" :resize="'none'" autosize class="areaInputStyle" type="textarea"
                maxlength="27" />
            </td>
          </tr>
          <tr>
            <td style="text-align: center;">当事人信息</td>
            <td colspan="4">
              <privy-info-select-return-array v-model="form.unitName" :isTable="true" maxLength="27"
                return-fields="A(B)" :return-array-template="[

                ]" @select="selectUnitUpdateData">
              </privy-info-select-return-array>
            </td>
          </tr>
          <tr>
            <td style="text-align: center;">告知事项</td>
            <td colspan="4">
              1.为便于当事人及时收到相关文书，当事人应当如实提供确切的送达地址。
              <br>
              2.确认的送达地址适用于行政执法全过程程序。如果送达地址有变更，应当及时书面告知我单位变更后的送达地址。
              <br>
              3.如果提供的地址不确切，或者不及时告知变更后的地址，使文书无法送达或者未及时送达，当事人将自行承担由此可能产生的后果。
              <br>
              4.接受电子送达方式的，以发送方设备显示发送成功视为送达。但接收方证明其到达特定系统的日期与发送方对应系统显示发送日期不一致的，以受送达人证明到达其特定系统的日期为准。
            </td>
          </tr>
          <tr>
            <td rowspan="5" style="text-align: center;">送达地址<br>及&nbsp;方&nbsp;式</td>
            <td style="text-align: center;">指定签收人</td>
            <td colspan="3">
              <el-input v-model="form.a4" :resize="'none'" autosize class="areaInputStyle" type="textarea"
                maxlength="21" />
            </td>
          </tr>

          <tr>
            <td style="height: 75px;text-align: center;">证件类型</td>
            <td>
              <el-input v-model="form.a5" :resize="'none'" autosize class="areaInputStyle" type="textarea"
                maxlength="24" />
            </td>
            <td style="text-align: center">证件号码</td>
            <td>
              <el-input v-model="form.a6" :resize="'none'" autosize class="areaInputStyle" type="textarea"
                maxlength="27" />
            </td>
          </tr>

          <tr>
            <td style="height: 50px;text-align: center;">确认送达<br>地&nbsp;&nbsp;&nbsp;&nbsp;址</td>
            <td colspan="3">
              <el-input v-model="form.a7" :resize="'none'" autosize class="areaInputStyle" type="textarea"
                maxlength="44" />
            </td>
          </tr>

          <tr>
            <td rowspan="2" style="text-align: center;">是否接受<br>电子送达</td>
            <td colspan="3" style="height: 25px;">
              <div>
                <input type="checkbox" v-model="form.checkbox1"
                  @click="form.checkbox2 = false" /><span>是&emsp;&emsp;</span>
                <input type="checkbox" v-model="form.checkbox2" @click="form.checkbox1 = false" /><span>否</span>
              </div>
            </td>
          </tr>
          <tr>
            <td colspan="3" style="height: 125px;">
              <div style="display: flex;">
                <div style="width: 5mm;">
                  <span><input type="checkbox" value="1" v-model="form.a9"></span>
                </div>
                <div>
                  <span>传真号码：</span>
                  <CrossRowInput v-model:value="form.a10" :line-config="a10Config"></CrossRowInput>
                </div>
              </div>
              <div style="display: flex;">
                <div style="width: 5mm;">
                  <span><input type="checkbox" value="1" v-model="form.a11"></span>
                </div>
                <div>
                  <span>电子邮件地址：</span>
                  <CrossRowInput v-model:value="form.a12" :line-config="a12Config"></CrossRowInput>
                </div>
              </div>
              <div style="display: flex;">
                <div style="width: 5mm;">
                  <span><input type="checkbox" value="1" v-model="form.a13"></span>
                </div>
                <div>
                  <span>其他：</span>
                  <CrossRowInput v-model:value="form.a14" :line-config="a14Config"></CrossRowInput>
                </div>
              </div>
            </td>
          </tr>

          <tr style="height: 125px;">
            <td style="text-align: center;">受送达人<br>确&nbsp;&nbsp;&nbsp;&nbsp;认</td>
            <td colspan="4" style="text-align: left;vertical-align: top; position: relative;">
              &nbsp;&nbsp;&nbsp;&nbsp;我已阅读(听明白)本确认书的告知事项，提供了上栏送达地址，确认了上栏送达方式，并保证所提供的送达地址各项内容是正确的、有效的。如在案件办理过程中送达地址发生变化，将及时通知贵单位。
              <div
                style="position: absolute; bottom: 10px; left: 20px; right: 20px; display: flex; justify-content: space-between; align-items: flex-end; margin-top: 20px;">
                <div style="display: flex; align-items: flex-end;">
                  签名：
                  <SignatureField label="签名1" sign-type="sign1" :img-url="form.img1"
                    @update:imgUrl="form.img1 = $event" />
                </div>
                <div>
                  <editable-textarea :text="form.date1" param-type="YYYYMMDD1"
                    @send-to-parent="receiveFromChild"></editable-textarea>
                </div>
              </div>
            </td>
          </tr>
          <tr style="height: 80px;">
            <td style="text-align: center;">行政执法<br>人&nbsp;&nbsp;&nbsp;&nbsp;员</td>
            <td colspan="4" style="position: relative;">
              <div
                style="position: absolute; bottom: 45px; left: 5px; right: 5px; display: flex; justify-content: space-between; align-items: flex-end; margin-top: 20px;">
                <div style="display: flex; align-items: flex-end;">
                  签名：
                  <SignatureField label="签名2" sign-type="sign2" :img-url="form.img2"
                    @update:imgUrl="form.img2 = $event" />
                  <span style="margin-left: 10px;">联系电话:</span>
                  <el-input style="width: calc(6 * 5mm); "
                    oninput="this.value = this.value.replace(/[^a-zA-Z0-9_-]/g, '')" v-model="form.a15" :resize="'none'"
                    autosize class="areaInputStyle" type="textarea" maxlength="12" />
                </div>
                <div style="text-align: right; margin-right: 20px;">
                  <editable-textarea :text="form.date2" param-type="YYYYMMDD2"
                    @send-to-parent="receiveFromChild"></editable-textarea>
                </div>
              </div>
              <div
                style="position: absolute; bottom: 10px; left: 5px; right: 5px; display: flex; justify-content: space-between; align-items: flex-end; margin-top: 20px;">
                <div style="display: flex; align-items: flex-end;">
                  签名：
                  <SignatureField label="签名3" sign-type="sign3" :img-url="form.img3"
                    @update:imgUrl="form.img3 = $event" />
                  <span style="margin-left: 10px;">联系电话:</span>
                  <el-input style="width: calc(6 * 5mm); "
                    oninput="this.value = this.value.replace(/[^a-zA-Z0-9_-]/g, '')" v-model="form.a16" :resize="'none'"
                    autosize class="areaInputStyle" type="textarea" maxlength="12" />
                </div>
                <div style="text-align: right; margin-right: 20px;">
                  <editable-textarea :text="form.date3" param-type="YYYYMMDD3"
                    @send-to-parent="receiveFromChild"></editable-textarea>
                </div>
              </div>
            </td>
          </tr>
          <tr>
            <td style="height: 25px; text-align: center;">备&nbsp;&nbsp;&nbsp;&nbsp;注</td>
            <td colspan="4">
              <el-input v-model="form.a17" :resize="'none'" autosize class="areaInputStyle" type="textarea"
                maxlength="27" />
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
import EditableTextarea from "@/views/template/EditableTextarea";
import { agencyName, sealName } from "../../utils/publicName.js"
import PrivyInfoSelectReturnArray from "@/views/template/PrivyInfoSelectReturnArray";
import SignatureField from "@/views/template/SignatureField";
import CrossRowInput from "@/views/template/CrossRowInput";

export default {
  components: {
    SignatureField,
    EditableTextarea,
    PrivyInfoSelectReturnArray,
    CrossRowInput,
  },

  data() {
    return {
      agencyName: agencyName,
      sealName: sealName,
      form: {},
      a10Config: {
        firstLine: { chars: 16 * 2 },
        middleLines: { count: 0, chars: 32 * 2 },
        lastLine: { chars: 0 * 2 }
      },
      a12Config: {
        firstLine: { chars: 14 * 2 },
        middleLines: { count: 0, chars: 32 * 2 },
        lastLine: { chars: 21 * 2 }
      },
      a14Config: {
        firstLine: { chars: 18 * 2 },
        middleLines: { count: 0, chars: 32 * 2 },
        lastLine: { chars: 21 * 2 }
      },
      isPdfExport: false, // 控制打印样式
    };
  },
  created() {
    //调用父页面函数获取文书数据
    window.parent.getTemplateData((data) => {
      this.form = data;
    })
    //将方法暴露在初始化加载中
    window.postForm = () => {
      this.postForm();
    }
  },
  mounted() {
    window.parent.changeTemplateDow();
  },
  methods: {
    // 导出为pdf
    exportPDF() {
      this.savePDF()
        .then((blob) => {
          const blobUrl = URL.createObjectURL(blob);

          // 先预览
          const previewWindow = window.open(blobUrl, '_blank');

          // 自动下载
          const fileName = `送达地址确认书.pdf`;
          const downloadLink = document.createElement('a');
          downloadLink.href = blobUrl;
          downloadLink.download = fileName;
          document.body.appendChild(downloadLink);
          downloadLink.click();
          document.body.removeChild(downloadLink);

          // 监听预览窗口关闭后释放内存
          if (previewWindow) {
            const timer = setInterval(() => {
              if (previewWindow.closed) {
                clearInterval(timer);
                URL.revokeObjectURL(blobUrl);
              }
            }, 1000);
          } else {
            setTimeout(() => URL.revokeObjectURL(blobUrl), 10000); // 兜底释放
          }
        })
        .catch(error => {
          console.error('导出PDF出错:', error);
          alert('导出失败，请重试或联系管理员');
        });
    },
    savePDF() {
      this.isPdfExport = true; // 激活PDF样式
      return new Promise((resolve, reject) => {
        this.$nextTick(() => {
          import('html2pdf.js').then((module) => {
            const html2pdf = module.default;

            //获取所有需要替换的 el-input
            const elInputs = document.querySelectorAll('.el-input__inner, .el-textarea__inner');

            //存储原始元素和它们的父节点，方便后续恢复
            const originalElements = [];

            elInputs.forEach((input) => {
              const div = document.createElement('div');
              div.style.whiteSpace = 'pre-wrap'; // 保留换行
              div.style.fontFamily = '仿宋';
              div.style.fontSize = '5mm';
              div.textContent = input.value; // 保留原内容（自动处理 \n 换行）
              div.style.lineHeight = '1.3';

              // 替换 el-input，并存储原始元素
              originalElements.push({
                parent: input.parentNode,
                original: input,
                replacement: div,
              });
              input.parentNode.replaceChild(div, input);
            });

            // 配置选项
            const opt = {
              margin: 0,
              image: {
                type: 'jpeg',
                quality: 0.98
              },
              html2canvas: {
                scale: 2,
                logging: false,
                useCORS: true
              },
              jsPDF: {
                unit: 'mm',
                format: 'a4',
                orientation: 'portrait'
              }
            };

            const element = document.getElementById('pdfDom');

            // 生成PDF Blob对象
            html2pdf()
              .set(opt)
              .from(element)
              .toPdf()
              .get('pdf')
              .then((pdf) => {
                const blob = pdf.output('blob');

                resolve(blob); // 返回Blob对象
              })
              .catch((error) => {
                reject(error);
              })
              .finally(() => {
                this.isPdfExport = false; // 恢复原始样式
                // 恢复原始input
                originalElements.forEach(({ parent, original, replacement }) => {
                  parent.replaceChild(original, replacement);
                });
              });
          }).catch((error) => {
            reject(error);
            this.isPdfExport = false;
            originalElements.forEach(({ parent, original, replacement }) => {
              parent.replaceChild(original, replacement);
            });
          });
        });
      });
    },
    //父页面提交按钮将调用此方法，此方法将文书数据回传到父页面的请求方法中
    postForm() {
      this.savePDF()
        .then((blob) => {


          // 创建FormData并添加文件
          const formData = new FormData();
          formData.append('file', blob, '送达地址确认书.pdf');

          window.parent.postTemplateDate(this.form, formData);
        })
        .catch(error => {
          console.error('整个保存PDF出错:', error);
        });
    },
    //选择日期时间
    receiveFromChild(data, type) {
      const TypeMap = {
        'YYYYMMDD1': 'date1',
        'YYYYMMDD2': 'date2',
        'YYYYMMDD3': 'date3',
      };
      if (TypeMap[type]) {
        this.form[TypeMap[type]] = data;
      }
    },
    // 选择单位
    selectUnitUpdateData(data) {
      data.forEach(item => {
        this.form[item.name] = item.value;
      })
    },
  },

}
</script>

<style scoped>
:deep(.el-button-print .el-button) {
  display: inline-flex !important;
  visibility: visible !important;
  opacity: 1 !important;
  width: auto;
  min-width: 100px;
  height: auto;
  padding: 8px 15px;
  background: #fff !important;
  color: #000 !important;
  border: none;
}

:deep(.el-textarea__inner) {
  box-shadow: 0 0 0 0;
  color: black;
  padding: 0;
  font-family: "仿宋", serif;
  font-size: 5mm;
  overflow-y: hidden;
  line-height: 1.3;
}

:deep(.el-textarea-hidden .el-textarea__inner) {
  box-shadow: 0 0 0 0;
  color: black;
  padding: 0;
  font-family: "仿宋", serif;
  font-size: 5mm;
  overflow-y: hidden !important;
  resize: none !important;
  height: auto !important;
}

.input-container {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
}

.inputStyleNoLine {
  border: none;
  outline: none;
  padding: 0px;
}

.typeSpan {
  cursor: pointer;
  font-size: 5mm;
}
</style>
